package com.zb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.*;
import com.zb.mapper.ZjCodeBatchMapper;
import com.zb.result.PageUtil;
import com.zb.service.*;
import com.zb.utils.RandomUtil;
import com.zb.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 编码批次表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-08-23
 */
@Service
public class ZjCodeBatchServiceImpl extends ServiceImpl<ZjCodeBatchMapper, ZjCodeBatch> implements ZjCodeBatchService {
    @Resource
    private ZjCodeBatchMapper codeBatchMapper;
    @Resource
    private ZjCodeBatchGoodsService codeBatchGoodsService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private ZjCodeService codeService;

    // 新增编码批次
    @Override
    public Long save(AccounLoginInfo loginInfo, String batchPrefix, CodeBatchVo codeBatchVo, Integer codeSource) {
        ZjCodeBatch batch = new ZjCodeBatch();
        batch.setId(IdWorker.getId());
        batch.setCustAccId(loginInfo.getCustAccId());
        batch.setType(codeBatchVo.getType());
        batch.setName(codeBatchVo.getName());
        batch.setCode((StringUtils.isBlank(batchPrefix)? "" : batchPrefix) + RandomUtil.dateRandom14());
        batch.setQty(codeBatchVo.getQty());
        batch.setCodeSource(codeSource);
        batch.setDisabled(false);
        batch.setCreateEmpId(loginInfo.getId());
        batch.setCreateEmp(loginInfo.getName());
        batch.setUpdateEmpId(loginInfo.getId());
        batch.setUpdateEmp(loginInfo.getName());
        this.save(batch);
        return batch.getId();
    }

    // 保存Excel导入的批次编码
    @Override
    public void saveExcelBatchCode(List<ZjCodeBatch> addCodeBatchList, List<ZjCodeBatch> updateCodeBatchList, List<ZjCodeBatchGoods> addCodeBatchGoodsList, List<ZjCodeBatchGoods> updateCodeBatchGoodsList) {
        if (CollectionUtil.isNotEmpty(addCodeBatchList)) {
            this.saveBatch(addCodeBatchList);
        }
        if (CollectionUtil.isNotEmpty(updateCodeBatchList)) {
            this.updateBatchById(updateCodeBatchList);
        }
        if (CollectionUtil.isNotEmpty(addCodeBatchGoodsList)) {
            codeBatchGoodsService.saveBatch(addCodeBatchGoodsList);
        }
        if (CollectionUtil.isNotEmpty(updateCodeBatchGoodsList)) {
            codeBatchGoodsService.updateBatchById(updateCodeBatchGoodsList);
        }
    }

    // 根据批次ID获取批编码
    @Override
    public List<ZjCodeBatch> getByIds(List<Long> idList) {
        if (null == idList || idList.isEmpty()) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjCodeBatch> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name", "code", "qty");
        wrapper.in("id", idList);
        return this.list(wrapper);
    }

    // 获取批次编码列表
    @Override
    public Map<String, Object> getList(Long custAccId, CodeBatchSelectVo selectVo) {
        PageUtil.setPageLimit(selectVo);
        List<Long> batchIds = null;
        // 获取商品ID
        if (null != selectVo.getBrandId() || null != selectVo.getTypeId()) {
            GoodsSelect goodsSelect = new GoodsSelect(custAccId, selectVo.getBrandId(), selectVo.getTypeId(), null);
            goodsSelect.setPage(selectVo.getPage());
            goodsSelect.setLimit(selectVo.getLimit());
            List<Long> goodsIds = null;
            goodsIds = goodsService.pageGetGoodsIds(goodsSelect);
            if (goodsIds.isEmpty()){
                goodsIds.add(-1L);
            }
            // 获取批次ID
            batchIds = codeService.pageGetBatchIds(custAccId, goodsIds, selectVo.getPage(), selectVo.getLimit());
            if (batchIds.isEmpty()){
                batchIds.add(-1L);
            }
        }
        List<ZjCodeBatch> batches = codeBatchMapper.getList(custAccId, batchIds, selectVo);
        // 查询激活数量
        List<CodeBatchListVo> activaCountList = codeService.getActivaCountByBatchIds(batches.stream().map(ZjCodeBatch::getId).toList());
        List<CodeBatchListVo> voList = batches.stream().map(batch -> {
            CodeBatchListVo vo = new CodeBatchListVo();
            BeanUtils.copyProperties(batch, vo);
            vo.setStatus(batch.getDisabled());
            vo.setCreateTime(batch.getGmtCreate());
            vo.setActivaCount(activaCountList.stream().filter(co -> Objects.equals(vo.getId(), co.getId())).map(CodeBatchListVo::getActivaCount).findFirst().orElse(0L));
            return vo;
        }).toList();
        return PageUtil.pageList(selectVo.getPage(), selectVo.getLimit(), codeBatchMapper.getListCount(custAccId, batchIds, selectVo), voList);
    }

    // 根据批次ID获取批次编码详情
    @Override
    public Object getDetailById(Long id) {
        ZjCodeBatch batch = this.getById(id);
        Assert.isTrue(null != batch, "参数[" + id + "]的数据不存在！");
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("id", batch.getId());
        resultMap.put("code", batch.getCode());
        resultMap.put("type", batch.getType());
        resultMap.put("createTime", batch.getGmtCreate());
        resultMap.put("createEmp", batch.getCreateEmp());
        return resultMap;
    }

    // 根据编码批次ID批量删除
    @Override
    @Transactional
    public void deleteByIds(List<Long> idList) {
        codeService.checkCodeRelationInfoForDeleteByBatchIds(idList);
        idList.forEach(t -> {
            codeService.deleteByBatchId(t);
        });
        this.removeByIds(idList);
    }

    // 批次编码下拉列表查询
    @Override
    public Map<String, Object> codeBatchPageSelect(Long custAccId, SelectVo selectVo) {
        PageUtil.setSelectPageLimit(selectVo);
        QueryWrapper<ZjCodeBatch> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name", "code");
        wrapper.eq("cust_acc_id", custAccId);
        if (StringUtils.isNotBlank(selectVo.getName())) {
            wrapper.like("code", selectVo.getName());
        }
        Page<ZjCodeBatch> page = this.page(new Page<>(selectVo.getPage(), selectVo.getLimit()), wrapper);
        List<BatchCodeSelectVo> voList = page.getRecords().stream().map(code -> {
            return new BatchCodeSelectVo(code.getId(), code.getName(), code.getCode());
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 批量更改编码商品信息
    @Override
    public void updateCodeGoods(AccounLoginInfo loginInfo, CodeBatchGoodsUpdateVo goodsUpdateVo) {
        codeService.updateCodeGoods(loginInfo, goodsUpdateVo);
    }

    // 根据编码批次ID导出所有编码
    @Override
    public ZjCodeBatch codeBatchExportById(Long batchId) {
        ZjCodeBatch codeBatch = this.getById(batchId);
        return codeBatch;
    }

    // 根据编码ID修改或删除编码批次信息
    @Override
    public void updateQtyByCodeIds(List<Long> codeIds) {
        if (null == codeIds || codeIds.isEmpty()) {
            return;
        }
        List<ZjCode> codes = codeService.getBatchIdByIds(codeIds);
        List<ZjCodeBatch> batchList = this.getByIds(codes.stream().map(ZjCode::getBatchId).distinct().toList());
        List<ZjCodeBatch> updates = new ArrayList<>();
        ZjCodeBatch batch = null;
        int qty = 0;
        for (ZjCodeBatch bt : batchList) {
            qty = (int) codes.stream().filter(co -> Objects.equals(bt.getId(), co.getBatchId())).count();
            batch = new ZjCodeBatch();
            batch.setId(bt.getId());
            batch.setQty(bt.getQty() - qty);
            updates.add(batch);
        }
        if (!updates.isEmpty()) this.updateBatchById(updates);
    }

}
